import os
import sys
import numpy as np

loss = 1e-3 # 容忍偏差，一般fp16要求绝对误差和相对误差均不超过千分之一
minimum = 10e-10

def verify_result(real_result, golden):
    # 读取二进制文件到本地的一个ndarray对象中
    real_result = np.fromfile(real_result, dtype=np.float16)  # 从bin文件读取实际运算结果，放到real_result向量中
    # 将向量转为8*3矩阵
    mat = real_result.reshape(8, 3)
    print(type(real_result))  # <class 'numpy.ndarray'>
    print("real_result=\n", real_result)
    print("mat=\n", mat)
    golden = np.fromfile(golden, dtype=np.float16) # 从bin文件读取预期运算结果

    result = np.abs(real_result - golden)  # 计算运算结果和预期结果偏差，矩阵减法
    print("矩阵减法result=\n", result)

    deno = np.maximum(np.abs(real_result), np.abs(golden)) # 获取最大值并组成新数组
    result_atol = np.less_equal(result, loss) # 计算绝对误差
    print("绝对误差result_atol=\n", result_atol)

    result_rtol = np.less_equal(result / np.add(deno, minimum), loss) # 计算相对误差
    print("相对误差result_rtol=\n", result_rtol)

    if not result_rtol.all() and not result_atol.all():
        if np.sum(result_rtol == False) > real_result.size * loss and np.sum(result_atol == False) > real_result.size * loss:
            print("[ERROR] result error")
            return False
    print("test pass")
    return True

if __name__ == '__main__':
    # verify_result(sys.argv[1],sys.argv[2])
    verify_result("./output/golden.bin", "./output/golden.bin")
